package com.smart.fourteen.hibernate.annotate.dao;

import com.smart.fourteen.hibernate.annotate.model.Topic;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
@Transactional
public class TopicDao{
    @Autowired
    private SessionFactory sessionFactory;

    //sessionFactory.getCurrentSession() need Transactional
    public void addTopic(Topic topic){
        sessionFactory.getCurrentSession().save(topic);
    }

    public void updateTopic(Topic topic){
        sessionFactory.getCurrentSession().update(topic);
    }

    public Topic getTopic(int id){
        return sessionFactory.getCurrentSession().get(Topic.class, id);
    }

    //使用HQL查询
    public List<Topic> findTopicByName(String topicName){
        //需要jdk1.8
        return (List<Topic>) sessionFactory.getCurrentSession().createQuery("from Topic t where t.name like ?1").setParameter(1, topicName+"%").list();
    }

    public long getTopicNum(){
        Object o = sessionFactory.getCurrentSession().createQuery("select count(t.id) from Topic t").iterate().next();
        return (Long) o;
    }

}
